package com.dkd.easybook.controller;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.dkd.common.annotation.Log;
import com.dkd.common.core.controller.BaseController;
import com.dkd.common.core.domain.AjaxResult;
import com.dkd.common.enums.BusinessType;
import com.dkd.easybook.domain.EbAttachments;
import com.dkd.easybook.service.IEbAttachmentsService;
import com.dkd.common.utils.poi.ExcelUtil;
import com.dkd.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
/**
 * 用户附件Controller
 *
 * @author itheima
 * @date 2024-12-12
 */
@Api(tags = "用户附件Controller")
@RestController
@RequestMapping("/easybook/attachments")
public class EbAttachmentsController extends BaseController {
    @Autowired
    private IEbAttachmentsService ebAttachmentsService;
    @Autowired
    private FileStorageService fileStorageService;
    /**
     * 查询用户附件列表
     */
    @ApiOperation("查询用户附件列表")
    @PreAuthorize("@ss.hasPermi('easybook:attachments:list')")
    @GetMapping("/list")
    public TableDataInfo list(EbAttachments ebAttachments) {
        startPage();
        List<EbAttachments> list = ebAttachmentsService.selectEbAttachmentsList(ebAttachments);
        return getDataTable(list);
    }
    //参数为ids，查询附件列表
    @ApiOperation("查询用户附件列表")
    @PreAuthorize("@ss.hasPermi('easybook:attachments:list')")
    @PostMapping("/listByIds")
    public TableDataInfo listByIds(@RequestBody List<Long> ids) {
        startPage();
        if (ids.size() > 0) {
            List<EbAttachments> listEbAttachments = new ArrayList<>();
            ids.stream()
                    .forEach(item -> {
                        listEbAttachments.add(EbAttachments.builder()
                                .attachmentId(item)
                                .build());
                    });
            List<EbAttachments> list = ebAttachmentsService.selectEbAttachmentsListByIds(listEbAttachments);
            return getDataTable(list);
        } else {
            return getDataTable(new ArrayList<>());
        }
    }
    /**
     * 导出用户附件列表
     */
    @ApiOperation("导出用户附件列表")
    @PreAuthorize("@ss.hasPermi('easybook:attachments:export')")
    @Log(title = "用户附件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EbAttachments ebAttachments) {
        List<EbAttachments> list = ebAttachmentsService.selectEbAttachmentsList(ebAttachments);
        ExcelUtil<EbAttachments> util = new ExcelUtil<EbAttachments>(EbAttachments.class);
        util.exportExcel(response, list, "用户附件数据");
    }
    /**
     * 获取用户附件详细信息
     */
    @ApiOperation("获取用户附件详细信息")
    @PreAuthorize("@ss.hasPermi('easybook:attachments:query')")
    @GetMapping(value = "/{attachmentId}")
    public AjaxResult getInfo(@PathVariable("attachmentId") Long attachmentId) {
        EbAttachments ebAttachments = new EbAttachments();
        ebAttachments.setAttachmentId(attachmentId);
        return success(ebAttachmentsService.selectEbAttachmentsByAttachmentId(ebAttachments));
    }
    /**
     * 新增用户附件
     */
    @ApiOperation("新增用户附件")
    @PreAuthorize("@ss.hasPermi('easybook:attachments:add')")
    @Log(title = "用户附件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EbAttachments ebAttachments) {
        return toAjax(ebAttachmentsService.insertEbAttachments(ebAttachments));
    }
    /**
     * 修改用户附件
     */
    @ApiOperation("修改用户附件")
    @PreAuthorize("@ss.hasPermi('easybook:attachments:edit')")
    @Log(title = "用户附件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EbAttachments ebAttachments) {
        return toAjax(ebAttachmentsService.updateEbAttachments(ebAttachments));
    }
    /**
     * 删除用户附件
     */
    @ApiOperation("删除改用户附件")
    @PreAuthorize("@ss.hasPermi('easybook:attachments:remove')")
    @Log(title = "用户附件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{attachmentIds}")
    public AjaxResult remove(@PathVariable Long[] attachmentIds) {
        return toAjax(ebAttachmentsService.deleteEbAttachmentsByAttachmentIds(attachmentIds));
    }
    //上传附件
    @ApiOperation("上传附件")
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {

            /*// 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;*/
            // 指定oss保存文件路径 dkd-images/2024/06/19/文件名
            String objectName = LocalDate.now()
                    .format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/";
            // 上传图片，返回文件信息
            FileInfo fileInfo = fileStorageService.of(file)
                    .setPath(objectName)
                    .upload();
            EbAttachments ebAttachments = new EbAttachments(null, fileInfo.getUrl(), "", fileInfo.getOriginalFilename(), fileInfo.getOriginalFilename(), fileInfo.getPath(), fileInfo.getPath(), fileInfo.getExt(), fileInfo.getContentType(), fileInfo.getPlatform(), fileInfo.getSize(), fileInfo.getCreateTime(), null, null, null);
            Integer result = ebAttachmentsService.insertEbAttachments(ebAttachments);
            if (result == 1) {
                return AjaxResult.success(ebAttachments);
            } else {
                return AjaxResult.error("上传失败");
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
